const App = getApp();
const api = require('../../../../utils/api.js');
const util = require('../../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true, //是否显示面板指示点
    autoplay: true, //是否自动切换
    interval: 3000, //自动切换时间间隔,3s
    duration: 1000, //  滑动动画时长1s

    //页面图片适配
    imgwidth: 0,
    imgheight: 0,
    imgwidth1: 0,
    imgheight1: 0,
    imgwidth2: 0,
    imgheight2: 0,
    windowWidth: wx.getSystemInfoSync().screenWidth,
    windowHeight: wx.getSystemInfoSync().windowHeight,

    actionSheetHidden: true,
    //设置页面显示按钮类型
    buttonType: 0,
    toastHidden: true,
    stores_id: '',
    stores_name: '',
    goods_id: '',
    doc_url: '',
    list: '',
    rps_Msg: "已复制淘口令，请前去淘宝下单支付"
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    console.log(" 商品详情 onLoad................................")
    console.log(options)

    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route


    console.log("pages>>>>>>>>>>>>>>>>>>>>>>>")
    console.log(pages)

    console.log("商品详情 scene................................")
    console.log(options.scene)


    this.setData({
      goods_id: options.goods_id,
      stores_id: options.stores_id
    })


/*   var shareTickets = options.shareTicket
     wx.getShareInfo({
       shareTicket: shareTickets[0],
      success: function (res) {
        console.log("KKKKKKKKKKKKKK   转发 get ShareInfo KKKKKKKKKKKKKKKKKKKK")
        console.log(res)
        console.log("encryptedData")
        var encryptedData = res.encryptedData;
        var iv = res.iv;
      }
    }) */
 




/*     wx.getShareInfo({
      shareTicket: shareTickets[0],
      success: function (res) {
        console.log("KKKKKKKKKKKKKK   转发 get ShareInfo KKKKKKKKKKKKKKKKKKKK")
        console.log(res)
        console.log(res.encryptedData)
        console.log(res.iv)

        var encryptedData = res.encryptedData;
        var iv = res.iv;
      }
    }) */





    /** 判断场景值，1044 为转发场景，包含shareTicket 参数 */
    if (options.scene) {
      console.log("-------------1044 1007---------------")
      if (options.scene == 1044 || options.scene == 1007){
        wx.getShareInfo({
          shareTicket: options.shareTicket,
          success: function (res) {
            var encryptedData = res.encryptedData;
            var iv = res.iv;
          }
        })
      }
    }




    //this.getGoodsMsg()
    //目前需要转发的 页面 暂时这么实现：
    //获得app_token和安全码security_code
    var that = this;
    const data = {
      app_id: App.globalData.app_id,
      private_key: App.globalData.private_key,
    };

    api.getTokenAndCode({
      data,
      success: (res) => {
        if (res.data.rsp_code == 'succ') {
          App.globalData.app_token = res.data.data.app_token;
          App.globalData.security_code = res.data.data.security_code;
          that.getGoodsMsg();//加载商品详情页
        } else if (res.data.rsp_code == 'fail') {
          console.log(res.data.error_code)
          console.log(res.data.error_msg)
        }
      }
    })
    //// end
  },


  //加载商品详情页
  getGoodsMsg() {
    const self = this;
    let data = {
      service: 'goods.psGoodsDetailFind',
      params: '{"goods_id":""}',
      url_type: 'goods',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }
    var jsons = JSON.parse(data.params);
    jsons["goods_id"] = self.data.goods_id;
    data.params = JSON.stringify(jsons);

    //标签状态切换查询

    api.reqData({
      data,
      success: (res) => {
        console.log("------------加载商品详情页------------------------")
        console.log(res.data)

        var productList = res.data.data.list
        var product = productList[0]
        //计算返款金额，保留两位小数（避免0.0098888情况） 映射到参数ts_price上
        var returnMomeny = (product.market_price - product.discount_price).toFixed(2);
        product.ts_price = returnMomeny;

        //处理预售商品的预售时间
        console.log(product.valid_thru)
        if (product.valid_thru != null) {

          console.log(product.valid_thru)
          var time1 = new Date().Format(product.valid_thru)
          var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");
          console.log(time1)
          console.log(time2)

          if (time1 > time2) {
            console.log("buttonType=9 为预售商品")
            this.setData({
              buttonType: 9,
            })
          }
        }

        //图片地址由https 改为 http
        var doc_url_list = res.data.data.doc_url
        //var doc_url_value = Object.keys(doc_url_list)
        var doc_url_key = Object.keys(doc_url_list)
        for (var i = 0; i < doc_url_key.length; i++) {
          doc_url_list[doc_url_key[i]] = doc_url_list[doc_url_key[i]].replace("https", "http")
        }


        self.setData({
          doc_url: doc_url_list,
          list: productList
        })
      },
    })
  },

  //立即领取
  modalTap: function (e) {

    if (App.globalData.hasLogin === false) {//需要登录

      wx.navigateTo({
        url: '/pages/login/login',
      })

    } else {

      //判断是否已经绑定默认门店
      const self = this;
      let data = {
        //service: 'stores.consumer.defaultStore',
        service: 'stores.consumer.favoriteStoreList',
        params: '{"consumer_id":"0bc323a0d01811e7ac35c39610748aaf","is_llm_stores":"Y"}',
        url_type: 'member',
        app_token: App.globalData.app_token,
        security_code: App.globalData.security_code
      }

      var json = JSON.parse(data.params);
      json.consumer_id = App.globalData.memberInfo.member_id;
      data.params = JSON.stringify(json);

      api.reqData({
        data,
        success: (res) => {
          //这个得写法和格式 setData({........})
          console.log(res.data);
          let stores_id = res.data.data.list.length;
          //let stores_id = ""
          if (stores_id == 0) {
            this.setData({
              actionSheetHidden: false
            })
          } else {
            this.setData({
              //buttonType: 1,
              toastHidden: true,
              stores_id: res.data.data.list[0].stores_id,
              stores_name: res.data.data.list[0].stores_name
            })
            //立即领取和复制淘宝口令两个按钮功能合并
            this.modalTap1();
          }
        },
      })


    }
  },

  //复制淘淘口令
  modalTap1: function (e) {
    const self = this;
    let data = {
      service: 'order.consumerFreeGetRecordCreate',
      //goods_code 从哪里来
      params: '{"consumer_id":"","stores_name":"","goods_url":"","recommend_stores_id":"","goods_code":"","mobile":"","member_id":"","nick_name":"","order_type":"taobao","data_source":"SJLY_17","payment_way_key":"ZFFS_01","version_number":""}',

      url_type: 'opsorder',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code

    }

    //组装动态数据
    var json = JSON.parse(data.params);
    //组装第一层数据
    json.goods_code = self.data.list[0].goods_code;
    json.recommend_stores_id = self.data.stores_id;
    json.stores_name = self.data.stores_name;
    json.mobile = App.globalData.memberInfo.mobile;
    json.member_id = App.globalData.memberInfo.member_id;
    json.consumer_id = App.globalData.memberInfo.member_id;
    json.nick_name = App.globalData.memberInfo.mobile;
    json.version_number = App.globalData.version;       //创建会过自营时传版本号
    //复制淘宝口令
    var product_source = self.data.list[0].product_source;
    json.goods_url = product_source.replace(/￥/g, '《');
    data.params = JSON.stringify(json);

    //let sign = util.getSign(data);
    //data.sign = sign;

    api.reqData({
      data,
      success: (res) => {
        console.log(res.data);
        if (res.data.rsp_code === "succ") {
          // this.setData({
          //   buttonType: 2,
          //   toastHidden: true,
          // }),
          //设置淘淘领变量到剪贴版
          wx.setClipboardData({
            data: product_source,
            success: function (res) {
              console.log(res)
            }
          })
          //跳转到订单待付款页面
          App.globalData.secondIndex = 1,
            App.globalData.status = 'processing',
            wx.switchTab({
              url: '/pages/buy/orderlist/orderlist',
              success: function (e) {
                var page = getCurrentPages().pop();
                if (page == undefined || page == null) return;
                page.initData();
                page.onLoad();
              }
            })

        } else {
          this.setData({
            toastHidden: false,
            rps_Msg: res.data.error_msg
          })
        }
      },
    })
  },


  actionSheetChange: function (e) {
    this.setData({
      actionSheetHidden: true
    })
  },
  modalChange1: function (e) {
    this.setData({
      toastHidden: true,
    })
  },

  //我的收藏，附近门店页面跳转  goodsType：0 精品自营  1 淘宝商品
  toshoplist: function () {
    let goods_id = this.data.goods_id
    let consumer_id = App.globalData.memberInfo.member_id
    //为防止回退后还浮动页面跳转前隐藏
    this.setData({
      actionSheetHidden: true
    })
    wx.navigateTo({
      url: '../../shoplist/shoplist?consumer_id=' + consumer_id + '&goodsType=' + 1 + '&goods_id=' + goods_id
    })
  },
  tonearshoplist: function () {
    let goods_id = this.data.goods_id
    //为防止回退后还浮动页面跳转前隐藏
    this.setData({
      actionSheetHidden: true
    })
    wx.navigateTo({
      url: '../../nearshoplist/nearshoplist?goodsType=' + 1 + '&goods_id=' + goods_id
    })
  },

  //商品图片适配
  imageLoad: function (e) {
    var windowWidth = this.data.windowWidth;
    var $width = e.detail.width;    //获取图片真实宽度  
    var $height = e.detail.height;
    var ratio = $width / $height;   //图片的真实宽高比例  
    //设置图片显示宽度,适配的比例，
    var viewWidth = windowWidth;
    var viewHeight = viewWidth / ratio;    //计算的高度值     
    this.setData({
      imgwidth: viewWidth,
      imgheight: viewHeight
    })
  },

  imageLoad1: function (e) {
    var windowWidth = this.data.windowWidth;
    var $width = e.detail.width;    //获取图片真实宽度  
    var $height = e.detail.height;
    var ratio = $width / $height;   //图片的真实宽高比例  
    //设置图片显示宽度,适配的比例，
    var viewWidth = windowWidth;
    var viewHeight = viewWidth / ratio;    //计算的高度值     
    this.setData({
      imgwidth1: viewWidth,
      imgheight1: viewHeight
    })
  },

  imageLoad2: function (e) {
    var windowWidth = this.data.windowWidth;
    var $width = e.detail.width;    //获取图片真实宽度  
    var $height = e.detail.height;
    var ratio = $width / $height;   //图片的真实宽高比例  
    //设置图片显示宽度,适配的比例，
    var viewWidth = windowWidth * 0.2;
    var viewHeight = viewWidth / ratio;    //计算的高度值     
    this.setData({
      imgwidth2: viewWidth,
      imgheight2: viewHeight
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {

    //转发设withShareTicket为true,可以二次转发
    wx.showShareMenu({
      withShareTicket: true
    })

    if (res.from === 'menu') {
      // 来自页面内转发按钮
      console.log(res.from)
      console.log(res.target)
    }

    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route 

    console.log("三个参数>>>>>>>>>>>>>>>>>>>>>>>")
    console.log(pages)
    console.log(currentPage)
    console.log(url)
    console.log(currentPage.data.goods_id)



    //var desc = "领有惠实惠商品";
    var title = " ￥" + this.data.list[0].discount_price
      + " (返还￥" + this.data.list[0].ts_price + ") |" + this.data.list[0].title;

    return {
      title:title,
      //desc:desc,
      //path: "/" + url + '?goods_id=' + currentPage.data.goods_id,
      success: function (res) {

        // 转发成功
        console.log(res)
        console.log("KKKKKKKKKKKKKK   转发转发转发 success 111111111")

        var shareTickets = res.shareTickets
        if (shareTickets){
          if (shareTickets.length == 0) {
            return false;
          }
          console.log("KKKKKKKKKKKKKK   转发转发转发 success 222222222")
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function (res) {

              console.log("KKKKKKKKKKKKKK   转发 get ShareInfo KKKKKKKKKKKKKKKKKKKK")

              console.log(res.encryptedData)
              console.log(res.iv)

              var encryptedData = res.encryptedData;
              var iv = res.iv;
            }
          })

        }

      },
      fail: function (res) {
        console.log("----------转发失败 fail--------------")
        console.log(res)
      }
    }


  }
})